package com.mike.blog.service.impl;

import com.mike.blog.constant.ApplicationConstant;
import com.mike.blog.entity.User;
import com.mike.blog.enums.ResultEnum;
import com.mike.blog.exception.ServiceException;
import com.mike.blog.form.LoginForm;
import com.mike.blog.repository.UserRepository;
import com.mike.blog.service.LoginService;
import com.mike.blog.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

/**
 * @author xiaozefeng
 * @date 2018-12-14 16:46
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean login(HttpServletResponse response, LoginForm loginForm) {
        String username = loginForm.getUsername();
        String password = loginForm.getPassword();
        User user = userRepository.findByName(username);
        if (user == null) {
            throw new ServiceException(ResultEnum.USER_NOT_EXISTS);
        }
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!user.getPassword().equals(md5DigestAsHex)) {
            throw new ServiceException(ResultEnum.INCORRECT_PASSWORD);
        }
        String tokenValue = Base64Utils.encodeToString((loginForm.getUsername()
                + ApplicationConstant.TOKEN_SEPARATOR
                + loginForm.getPassword()).getBytes(Charset.forName("utf-8")));
        CookieUtil.markAsLoginSuccess(response, tokenValue);
        return true;
    }
}
